import React, { Component } from 'react'
import styled from 'styled-components'
import { connect } from 'react-redux'
import { Modal } from 'antd-mobile';
import CartList from '@/components/cartList'
import ToTalCheckCom from '@/components/totalCheck'
import TotalPrice from '@/components/totalPrice'
import * as type from '@/store/actionCreator.js'

class CartCom extends Component {
  render() {
    const { list,
      addCart,
      removeCart,
      totalCheck,
      handleTotalCheck,
      handleItemChange,
    } = this.props;
    return (
      <CartWrpper className="cart-wrapper">
        {/* 全选组件 */}
        <ToTalCheckCom
          totalCheck={totalCheck}
          totalEvent={(flag) => handleTotalCheck(flag)}
        />
        {/* 购物车列表组件 */}
        <CartList
          totalCheck={totalCheck}
          itemEvent={(opt) => handleItemChange(opt)}
          list={list}
          addCart={(index) => addCart(index)}
          removeCart={(index, item) => removeCart(index, item)}
        />
        {/* 总价组件 */}
        <TotalPrice>总价格：{this.getTotalPrice()}</TotalPrice>
      </CartWrpper>
    )
  }
  // 计算总价功能
  getTotalPrice() {
    // 报错往前找
    return this.props.list.length && this.props.list.reduce((num, item) => {
      return num + item.price * item.count;
    }, 0)
  }
}

const alert = Modal.alert;
// console.log(Modal, ':modal---')
const showAlert = (calllback) => {
  alert('Delete', 'Are you sure???', [
    {
      text: 'Cancel', onPress: () => {
        console.log('cancel')
        calllback && calllback('cancel')
      }, style: 'default'
    },
    {
      text: 'OK', onPress: () => {
        console.log('ok')
        calllback && calllback('ok')
      }
    },
  ]);
};

const mapStateToProps = (state) => {
  return {
    list: state.cart.cartData,
    totalCheck: state.cart.totalCheck
  }
}

const mapActionToProps = (dispatch) => {
  return {
    // 全选
    handleTotalCheck(flag) {
      const action = type.changeTotalCheck(flag)
      dispatch(action)
    },
    // 每一个的单项
    handleItemChange(opt) {
      const action = type.changeItemCheck(opt)
      dispatch(action)
    },
    addCart(index) {
      const action = type.addCartItem(index)
      dispatch(action)
    },
    removeCart(index, item) {
      // 点击删除的时候， 判断，如果为 count<=1 调弹出框
      if (item.count <= 1) {
        showAlert((btnMsg) => {
          console.log(btnMsg, '---msg---')
          if (btnMsg === 'ok') {
            const action = type.deleteItem(index)
            dispatch(action)
          }
        })
      } else {
        const action = type.removeItem(index)
        dispatch(action)
      }
    }
  }
}

export default connect(mapStateToProps, mapActionToProps)(CartCom)


const CartWrpper = styled.div`
  width: 100%;
  input {
    width: 40px;
    height: 40px;
  }
`;